const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

const { executeCommand, executeCommandWithTimeout } = require("./utils/system")
const { csvToJson } = require("./utils/csvToJson")
const { deleteLocalFile, deleteFilesByFilename, deleteFolder, clearFolder } = require("./utils/fileDeal")
let wifiFilePath = path.join(__dirname, "./output-01.csv");
const { storage } = require("./utils/store");
// let deviceFilePath = path.join(__dirname, "./handshake-01.csv");
const getJson = async (filePath) => {
    console.log("getJson")

    return new Promise(async (resolve, reject) => {
        let resultJson = await csvToJson(filePath)
        // console.log("resultJson",resultJson)
        // return
        resolve(resultJson)
    })
}

const run = async () => {
    // 从csv文件中获取json文件 
    let resultJons = await getJson(wifiFilePath)
    let wifiArray = resultJons.one
    // 读取每个wifi的设备存储在本地文件
    let deviceInfoArray = []

    // 遍历wifi信息 
    // wifiArray.forEach(async (element, elementIndex) => {
        let index  = 1
    for (const element of wifiArray){
        let BSSID = element['BSSID'].trim()  //wifi 地址 
        let channel = element[' channel'].trim() // 通道
        let ESSID = element[' ESSID'].trim() // wifi name
        
        console.log("开始扫描第"+index+"个wifi:"+ESSID +'共有wifi设备个数'+wifiArray.length)
        index+=1
        // console.log("--------------------------")
        // console.log("BSSID",BSSID)
        // console.log("ESSID",ESSID)
        // console.log(" channel",channel)
        // console.log(ESSID.includes("ChinaNet"))

        // // if(elementIndex == 0 ){ // first to crwal device
        //     // console.log(`airodump-ng -c ${channel} --bssid ${BSSID} -w /home/apple/桌面/handshake wlan0mon`)
        // // }
        // if (ESSID.includes("LINK_56EE")) {
        // 监听10秒 获取路由器设备下的地址   会生成handshake-01.csv文件
        const commandC = `sudo airodump-ng -c ${channel} --bssid ${BSSID} -w /home/apple/桌面/wifisck/handshake/handshake wlan0`
        // console.log("commandC", commandC)
        const command = 'sudo';
        const args = [
            'airodump-ng',
            '-c',
            channel,
            '--bssid',
            BSSID,
            '-w',
            '/home/apple/桌面/wifisck/handshake/handshake',
            'wlan0',
        ];
        await executeCommand(command, args)
        let deviceFilePath = path.join(__dirname, "./handshake/handshake-01.csv");

        // 读取文件handshake-01.csv 转成json
        let tempDeviceArray = await getJson(deviceFilePath)
        let deviceArray = tempDeviceArray.two
        
        // console.log("@@lastArr", Array.isArray(lastArr), Array.isArray(deviceArray), lastArr)
        console.log("deviceArray", deviceArray)
        // let newArr = [...lastArr, ...deviceArray]
        // console.log("newArr", newArr.length)
        // console.log("添加设备内容", deviceArray)
        console.log("扫描该wifi下有:"+ deviceArray.length+ "个设备")
        deviceInfoArray = [ ...deviceInfoArray , ...deviceArray]
        console.log("采集有效设备" + deviceInfoArray.length)
        clearFolder(path.join(__dirname, "./handshake"))
        // }
        // console.log("--------------------------")
    };
    console.log("结束扫描开始写入文件...")
    console.log("ressult length"+deviceInfoArray.length)

    // 将文件读取
    storage.set(deviceInfoArray)
}

run()

// try {
//     filePath = path.join(__dirname, "./output-01.csv")
//     await deleteLocalFile(filePath)
// } catch (error) {
//     console.log("delete dir failed or dir not exist")
// }
// error "stdout maxBuffer length exceede" so  run
// sudo airmon-ng
//                   sudo airmon-ng start wlan0

// sudo airodump-ng wlan0mon -w output --output-format csv --write-interval 10
// sudo airodump-ng wlan0 -w output --output-format csv --write-interval 10


// console.log("result", resultJson)
// resultJons = resultJson[0]

// 